﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Sparrow.CMS
{
    using Sparrow.Web.Router;
    using System.Threading.Tasks;

    public class PageContentHttpHandler:IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            var router = context.Request.FindRouter();

            var routerHandlers = CallContext.Components.FindAll<IRouterHandler>();

            Parallel.ForEach(routerHandlers,handler=>handler.Process(router));

            var content = router.FindContent();

            var html = "";
            if (content != null)
            {
                var viewEngine = Facotry.FindViewEngine(content.LayoutName);

                var widgets = content.Layout.Widgets;

                var widgetContents = new Dictionary<string, string>();

                var actionHandlers = CallContext.Components.FindAll<IActionHandler>();


                Parallel.ForEach(widgets, widget =>
                {
                    widgetContents.Add(widget.Name, "");
                    var actions = widget.GetActions(content);
                    foreach(var action in actions)
                    {
                        Parallel.ForEach(actionHandlers, handler => handler.Process(action));

                        var viewEngineForWidget = Facotry.FindViewEngine(action.ViewName);

                        var widgetContent = viewEngineForWidget.RenderView(action.ViewName, content, action.Execute(content));
                        widgetContents[widget.Name] += html;
                    };
                });

                html = viewEngine.RenderView(content.Layout.Name, content, widgetContents);
            }

            //todo: combine scripts/stylesheets

            context.Response.Write(html);
            context.Response.End();
        }

        #endregion
    }
}
